var basePage = require('../../../common/BasePage');
Page({
    behaviors: [basePage],
    data: {
        /**仓库信息 */
        areaData: [],
        /**仓库索引 */
        tabIndex: 0,
        cartList: [],
        selected_status: 0, //是否全选
        allChecked: false, //全选
        total_price: 0, //选中项价格总计
		wh_id:1,
		activeCar:"flower",//flower:鲜花交易,seckill:秒杀,dounan:斗南专享
        areaArr:[],
        warehouse:{},
        carCount:{},//购物车数量统计
        // setTimeId: 0, //延迟修改后台数量的计时id
        // checked: false,
            /**不包含昆明总仓的 数组 */
    
    },
    onLoad() {

        // this.req_cart(warehouse.wh_id)
    },
    onShow() {
        this.setData({
            tabIndex:0,
            activeCar:'flower'
        })
        this.getWhList()
        // if (!this.data.areaData || !this.data.areaData.length) {
        //     let areaData = getApp().globalData.areaData;
        //     let areaArr = [];
        //     for (let i = 1; i < areaData.length; i++) {
        //         areaArr.push(areaData[i]);
        //     }
        //     this.setData({
        //         areaData ,
        //         areaArr
        //     })
        // }
        // console.log("this.data.tabIndex",this.data.tabIndex);
        
        
    },
    getWhList(){
        this.request({
            url: this.data.host + '/home/cart/warehouse',
        }, res=>{
            this.setData({
                areaArr:res.data,
                areaData:res.data,
                
            })
            if(res.data.length>0){
                this.setData({
                    wh_id:this.data.areaData[this.data.tabIndex].wh_id
                })
                this.req_cart(this.data.areaData[this.data.tabIndex].wh_id)
                this.getCount(this.data.areaData[this.data.tabIndex].wh_id)
               
            }else{
                this.setData({
                    wh_id:1
                })
                this.req_cart(1)
                this.getCount(1)
            }
            
        });
    },
    getCount(wh_id){
        this.request({
            url: this.data.host + '/home/cart/count',
            data: {
                wh_id: wh_id
            }
        }, res=>{
            this.setData({
                carCount:res.data
            })
            console.log("carCount",this.data.carCount)
        });
    },
    login_reload() {
        this.getWhList()
        // this.req_cart(this.data.areaData[this.data.tabIndex].wh_id)
    },
	changTab(e){
		this.setData({
			activeCar:e.currentTarget.dataset.type
		})
        this.req_cart(this.data.areaData[this.data.tabIndex].wh_id)
        
	},
    /**获取购物车信息 */
    req_cart(wh_id = 1) {
        //请求购物车数据
        var url='/home/cart/index?wh_id=' + wh_id+"&from="+this.data.activeCar
        if(this.data.activeCar=="pindan"){
            url="/home/wh/cart/index?wh_id="+wh_id
        }
        this.request({
            url: this.data.host + url,
            loadingTip: '购物车正在驶来...'
        }, this.get_cart_ok);
    },
    area_change(e) {
        let index= e.currentTarget.dataset.index;
        // let detail = e.detail;
        // getApp().globalData.warehouse = this.data.areaData[index];
		console.log("whid",this.data.areaData[index])
        // this.data.tabIndex = index;
        this.setData({
            tabIndex:index,
			wh_id:this.data.areaData[index].wh_id,
            activeCar:"flower",
            warehouse:this.data.areaData[index]
        })
        this.req_cart(this.data.areaData[index].wh_id)
        this.getCount(this.data.areaData[index].wh_id)
    },
    add_often(e) {
        this.request({
            url: this.data.host + '/home/often/addToOften',
            data: {
                pid: e.currentTarget.dataset.pid
            },
            loadingTip: '正在提交',
            method: "post"
        }, this.add_often_ok);
    },
    add_often_ok(res) {
        wx.showModal({
            cancelText: '继续添加',
            confirmText: '常购清单',
            content: '是否前往常购清单',
            showCancel: true,
            title: '设置成功',
            success: (result) => {
                if (result.confirm) {
                    // console.log("跳转完善页面");
                    wx.navigateTo({
                        url: '/pages/cls/often/List',
                    })
                }
            },
        })
    },
    get_cart_ok(res) {
        // console.log("get_cart_ok",res);
        res.data.map(val => {
            val.thumb = this.get_thumb(val.product_img);
        })
        this.setData({
            cartList: res.data,
            selected_status: res.selected_status,
            total_price: res.total.total_price * 100,
        });
    },
    /**
     * 购物车选中/取消事件
     * @param {currentTarget} e 
     */
    cart_change({
        currentTarget
    }) {
        console.log("cart_change", currentTarget);
        let cartList = this.data.cartList;
        cartList[currentTarget.dataset.index].selected = !cartList[currentTarget.dataset.index].selected;
        this.setData({
            cartList: cartList
        });
        let that = this;
        //更改后台选择状态   cart_id:currentTarget.dataset.cart_id,
        var url="/home/cart/selectCart"
        if(this.data.activeCar=="pindan"){
            url="/home/wh/cart/selectCart"
        }
        this.request({
            url: this.data.host +url,
            data: {
                cart_id: currentTarget.dataset.cart_id,
            },
            method: 'post'
        }, res => {}, res => { //后台更改失败，恢复前端原状态
            wx.showToast({
                title: res.msg || '操作购物车失败，请稍后再试',
                icon: 'none'
            });
            //恢复购物车状态
            cartList[currentTarget.dataset.index].selected = !cartList[currentTarget.dataset.index].selected;
            that.setData({
                cartList: cartList
            });
        }, that.update_cartmsg(cartList));
    },
    /**
     * 全选、全取消
     */
    cartAll_change() {
        var url='/home/cart/selected?wh_id='
        if(this.data.activeCar=="pindan"){
            url='/home/wh/cart/selected?wh_id='
        }
        this.request({
            url: this.data.host + url + this.data.areaData[this.data.tabIndex].wh_id,
            method: 'post',
            loadingTip: '修改中'
        }, this.cartAll_ok);
    },
    /**
     * 全选或取消成功
     */
    cartAll_ok(res) {
        let selected_status = !this.data.selected_status;
        let cartList = this.data.cartList;
        let total_price = 0;
        for (let i = 0; i < cartList.length; i++) {
            let cart = cartList[i];
            cart.selected = selected_status;
            if (selected_status) {
				// if(cart.grade_level!=0){
				// 	total_price += cart.product_price * cart.product_number * 100;
				// }else{
				// 	total_price += cart.vip_price * cart.product_number * 100;
                // }
                
                if(cart.product_price!=cart.vip_price&&cart.vip_price){
                    total_price += cart.vip_price * cart.product_number;
                }else{
                    total_price += cart.product_price * cart.product_number;
                }
                
            }
        }
        console.log("total_price@@", total_price)
        this.setData({
            total_price: total_price * 100,
            selected_status: selected_status,
            cartList: cartList
        });
    },
    /**
     * 刷新购物车总金额和全选状态
     *  @param {[]} cartList 当前的购物车数组 
     */
    update_cartmsg(cartList) {
        let selected_status = 1;
        let total_price = 0;
        for (let i = 0; i < cartList.length; i++) {
            let cart = cartList[i];
            if (!cart.selected) {
                selected_status = 0;
            } else {
				// if(cart.grade_level!=0){
				// 	total_price += cart.product_price * cart.product_number;
				// }else{
				// 	total_price += cart.vip_price * cart.product_number;
                // }
                if(cart.product_price!=cart.vip_price&&cart.vip_price){
                    total_price += cart.vip_price * cart.product_number;
                }else{
                    total_price += cart.product_price * cart.product_number;
                }
                
            }
        }
        this.setData({
            selected_status: selected_status,
            total_price: total_price * 100
        });
    },
    /**
     * 购物车单个数量变化
     * @param {*} e 
     */
    num_change(e) {
        // console.log("num_change", e);
        // console.log(this.data.setTimeId)
        let that = this;
        if (e.detail == 0) {
            wx.showModal({
                content: '是否删除该产品？',
                success(obj) {
                    if (obj.confirm) { //删除
                        that.delete_cart(e.currentTarget.dataset.cart_id, e.currentTarget.dataset.index)
                    }
                }
            })
        } else if (e.currentTarget.dataset.product_number != e.detail) {
            this.req_addCart(e.currentTarget.dataset.cart_id, e.currentTarget.dataset.product_number, e.detail, e.currentTarget.dataset.index);
        }

    },
    /**
     * 购物车单个删除按钮点击
     * @param {obj} param0 
     */
    delete_click(e) {
        // console.log("delete_click", currentTarget);
        this.delete_cart(e.currentTarget.dataset.cart_id, e.currentTarget.dataset.index)
    },
    /**删除购物车 */
    delete_cart(cart_id, index) {
        var url= '/home/cart/cartDelete'
        if(this.data.activeCar=='pindan'){
            url= "/home/wh/cart/cartDelete"
        }
        this.request({
            url: this.data.host + url,
            method: 'post',
            data: {
                cart_ids: cart_id
            },
            loadingTip: '正在删除中...'
        }, res => {
            this.delete_ok(res, index);
        });
    },
    /**
     * 单个购物车删除成功
     * @param {obj} res 后台返回得提示信息
     * @param {int} index 删除的购物车索引
     */
    delete_ok(res, index) {
        console.log("delete_ok", res, index);
        wx.showToast({
            title: res.msg,
        })
        this.data.cartList.splice(index, 1);
        this.setData({
            cartList: this.data.cartList
        })
        this.update_cartmsg(this.data.cartList);
    },
    /**
     * 请求后台更改购物车数量
     * @param {int} cart_id 购物车id
     * @param {int} oldNum  
     * @param {int} newNum 
     */
    req_addCart(cart_id, oldNum, newNum, index) {
        console.log("req_addCart", cart_id, oldNum, newNum);
        // this.setTimeId = 0;
        var url="/home/cart/cartSku"
        if(this.data.activeCar=="pindan"){
            url="/home/wh/cart/cartSku"
        }
        this.request({
            url: this.data.host + url,
            method: 'post',
            data: {
                cart_id,
                nums: newNum
            },
            loadingTip: '修改中'
        }, res => {
            this.cartSku_ok(res, index, newNum)
        });
    },
    /**
     * 成功修改数量
     * @param {*} res 后台返回的数据
     * @param {int} index 当前修改的购物车在列表中的索引
     */
    cartSku_ok(res, index, newNum) {
        console.log("cartSku", res, index);
        this.data.cartList[index].product_number = newNum;
        // console.log
        this.setData({
            cartList: this.data.cartList,
            total_price: res.data.total_price * 100
        })
    },
    /*点击结算*/
    submit_order() {
        var url='/home/cart/new_cart?wh_id=' + this.data.areaData[this.data.tabIndex].wh_id+"&from="+this.data.activeCar
        if(this.data.activeCar=="pindan"){
            url="/home/wh/cart/cart?wh_id="+this.data.areaData[this.data.tabIndex].wh_id
        }
        this.request({
            url: this.data.host + url
        }, this.submit_ok);
        // wx.navigateTo({
        //     url: '/pages/order_confirm/order_confirm',
        // })
    },
    submit_ok(res) {
        console.log('/home/cart/cart', res);
        res.data.cashier_decca = this.get_thumb(res.cashier_decca, 'wide');
        let that = this;
        wx.navigateTo({
            // url: '/pages/order_confirm/order_confirm',
            url: '/pages/neworder_confirm/order_confirm',
            success: function (obj) {
                // 通过eventChannel向被打开页面传送数据

                obj.eventChannel.emit('orderData', {
                    wh_id: that.data.areaData[that.data.tabIndex].wh_id,
                    warehouse:that.data.areaData[that.data.tabIndex],
                    index: that.data.areaData[that.data.tabIndex].index,
                    data: res.data,
                    m_addr: res.m_addr,
					activeCar:that.data.activeCar,
					wuliu:res.data.freight_list,
					specialList:res.data.extra_list,
                    pack_list:res.data.pack_list,
                    buyType:0,
                    order_pei_type:res.order_pei_type,
                    orderWarehouse:res.warehouse
                })
            }
        })
    },
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		return {
			title: '源花采购',
			path: 'pages/cls/index/index?uid=' + +getApp().globalData.userInfo.uid,
			success: (res) => {
				console.log("转发成功", res);
			},
			fail: (res) => {
				console.log("转发失败", res);
			}
		}
	}
})